<template>
  <div>
    <TopNav :title="$route.query.title"></TopNav>
    <div class="main">
      <van-address-edit
        ref="addAddress"
        :area-list="areaList"
        show-delete
        show-postal
        show-set-default
        show-search-result
        :address-info="addressInfo"
        :search-result="searchResult"
        :area-columns-placeholder="['请选择', '请选择', '请选择']"
        @save="onSave"
        @delete="onDelete"
      ></van-address-edit>
    </div>
  </div>
</template>

<script>
import {
  addAddress,
  updateAddress,
  getAddressDetail,
  DeleteAddress,
} from "@/api/index";
import { areaList } from "@vant/area-data";
import TopNav from "@/components/topNav.vue";
export default {
  name: "addressAdd",
  created() {
    if (this.$route.query.title == "添加") {
      return;
    }
    this.getDddress();
  },
  data() {
    return {
      areaList,
      searchResult: [],
      addressInfo: {},
    };
  },
  methods: {
    onSave(content) {
      const params = {
        userName: content.name,
        userPhone: content.tel,
        provinceName: content.province,
        cityName: content.city,
        regionName: content.county,
        detailAddress: content.addressDetail,
        defaultFlag: content.isDefault ? 1 : 0,
        postalCode:content.postalCode
      };
      if (this.$route.query.title == "添加") {
        addAddress(params).then(() => {
            this.$router.replace("/addressList")
          });
      } else {
        params['addressId']=this.$route.query.id
        updateAddress(params)
          .then(() => {
            this.$router.replace("/addressList")
          });
      }
    },
    onDelete() {
      DeleteAddress(this.$route.query.id).then((data) => {
        this.$router.replace("/addressList")
      });
    },
    getAreaCode(area) {
      for (let k in areaList.county_list) {
        if (areaList.county_list[k].includes(area)) {
          return k;
        }
      }
    },
    getDddress() {
      getAddressDetail(this.$route.query.id).then((data) => {
        this.addressInfo = {
          name: data.data.userName,
          id: data.data.userId,
          tel: data.data.userPhone,
          addressDetail: data.data.detailAddress,
          isDefault: data.data.defaultFlag,
          areaCode: this.getAreaCode(data.data.regionName),
        };
      });
    },
  },
  components: { TopNav },
};
</script>
<style scoped>
.main {
  margin-top: 1rem;
}
</style>